package com.baozhun.mall.common.util.onkeylogin;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.baozhun.mall.common.R;
import com.baozhun.mall.common.activity.WebContainerActivity;
import com.baozhun.mall.common.arouter.RoutePath;
import com.baozhun.mall.common.util.Constants;
import com.mobile.auth.gatewayauth.AuthRegisterViewConfig;
import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.ResultCode;
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate;

import org.json.JSONException;
import org.json.JSONObject;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static com.baozhun.mall.common.util.onkeylogin.OneKeyLoginHelper.NEED_INTERCEPTOR;
import static com.blankj.utilcode.util.SizeUtils.dp2px;


/**
 * 号码栏水平位置的自定义view 推荐使用addAuthRegistViewConfig 可以添加到相对精准的位置
 */
public class CustomViewConfig extends BaseUIConfig {
    private final String TAG = "CustomViewConfig";

    public CustomViewConfig(Activity activity, PhoneNumberAuthHelper authHelper) {
        super(activity, authHelper);
    }

    @Override
    public void configAuthPage() {
        mAuthHelper.setUIClickListener((code, context, jsonString) -> {
            JSONObject jsonObj = null;
            try {
                if (!TextUtils.isEmpty(jsonString)) {
                    jsonObj = new JSONObject(jsonString);
                }
            } catch (JSONException e) {
                jsonObj = new JSONObject();
            }
            switch (code) {
                //点击授权页默认样式的返回按钮
                case ResultCode.CODE_ERROR_USER_CANCEL:
                    Log.e(TAG, "点击了授权页默认返回按钮");
                    mAuthHelper.quitLoginPage();
                    break;
                //点击授权页默认样式的切换其他登录方式 会关闭授权页
                //如果不希望关闭授权页那就setSwitchAccHidden(true)隐藏默认的  通过自定义view添加自己的
                case ResultCode.CODE_ERROR_USER_SWITCH:
                    ARouter.getInstance().build(RoutePath.Me.LOGIN).withBoolean(NEED_INTERCEPTOR, false).navigation();
                    break;
                //点击一键登录按钮会发出此回调
                //当协议栏没有勾选时 点击按钮会有默认toast 如果不需要或者希望自定义内容 setLogBtnToastHidden(true)隐藏默认Toast
                //通过此回调自己设置toast
                case ResultCode.CODE_ERROR_USER_LOGIN_BTN:
                    if (!jsonObj.optBoolean("isChecked")) {
//                            Toast.makeText(mContext, R.string.custom_toast, Toast.LENGTH_SHORT).show();
                    }
                    break;
                //checkbox状态改变触发此回调
                case ResultCode.CODE_ERROR_USER_CHECKBOX:
                    Log.e(TAG, "checkbox状态变为" + jsonObj.optBoolean("isChecked"));
                    break;
                //点击协议栏触发此回调
                case ResultCode.CODE_CLICK_AUTH_PRIVACY_WEBURL:
                    Log.e(TAG, "点击协议，" + "name: " + jsonObj.optString("name") + ", url: " + jsonObj.optString("url"));
                    WebContainerActivity.Companion.start(mActivity, jsonObj.optString("name"), jsonObj.optString("url").replace("《", "").replace("》", ""));
                    break;
                case ResultCode.CODE_ERROR_USER_PROTOCOL_CONTROL:
                    Log.e(TAG, "点击协议，" + "name: " + jsonObj.optString("name") + ", url: " + jsonObj.optString("url"));
                    WebContainerActivity.Companion.start(mActivity, jsonObj.optString("url"), jsonObj.optString("name").replace("《", "").replace("》", ""));
                    break;
                //用户调用userControlAuthPageCancel后左上角返回按钮及物理返回键交由sdk接入方控制
                case ResultCode.CODE_ERROR_USER_CONTROL_CANCEL_BYBTN:
                    Log.e(TAG, "用户调用userControlAuthPageCancel后使用左上角返回按钮返回交由sdk接入方控制");
                    mAuthHelper.quitLoginPage();
                    break;
                //用户调用userControlAuthPageCancel后物理返回键交由sdk接入方控制
                case ResultCode.CODE_ERROR_USER_CONTROL_CANCEL_BYKEY:
                    Log.e(TAG, "用户调用userControlAuthPageCancel后使用物理返回键返回交由sdk接入方控制");
                    mAuthHelper.quitLoginPage();
                    break;

                default:
                    break;

            }

        });
        mAuthHelper.removeAuthRegisterXmlConfig();
        mAuthHelper.removeAuthRegisterViewConfig();
        //二次弹框自定义
        mAuthHelper.removePrivacyAuthRegisterViewConfig();
        mAuthHelper.removePrivacyRegisterXmlConfig();
        mAuthHelper.addPrivacyRegisterXmlConfig(new AuthRegisterXmlConfig.Builder().setLayout(R.layout.item_custom_privacy_port, new AbstractPnsViewDelegate() {
            @Override
            public void onViewCreated(View view) {
                findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mAuthHelper.quitPrivacyPage();
                    }
                });
            }
        }).build());
        //切换登录方式text
        mAuthHelper.addAuthRegistViewConfig("switch_msg", new AuthRegisterViewConfig.Builder().setView(initSwitchView(390 - 50)).setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY).setCustomInterface(context -> {
            ARouter.getInstance().build(RoutePath.Me.LOGIN).withBoolean(NEED_INTERCEPTOR, false).navigation();
            mAuthHelper.quitLoginPage();
        }).build());
        //返回按钮
//        mAuthHelper.addAuthRegistViewConfig("back_btn", new AuthRegisterViewConfig.Builder()
//                .setView(initCloseBtn())
//                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_TITLE_BAR)
//                .setCustomInterface(context -> {
//                    mAuthHelper.quitLoginPage();
//                }).build());
        //背景图，返回按钮
        mAuthHelper.addAuthRegisterXmlConfig(new AuthRegisterXmlConfig.Builder().setLayout(R.layout.widget_authsdk_custom_layout, new AbstractPnsViewDelegate() {
            @Override
            public void onViewCreated(View view) {
                final RelativeLayout fly_container = view.findViewById(R.id.fly_container);
                ImageView imageView = new ImageView(fly_container.getContext());
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setImageResource(R.drawable.bg_login);
                fly_container.addView(imageView, params);
                //添加关闭按钮
                ImageView closeImageView = initCloseBtn();
                closeImageView.setOnClickListener(v -> {
                    mAuthHelper.quitLoginPage();
                });
                fly_container.addView(closeImageView);
            }
        }).build());
        int authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
        if (Build.VERSION.SDK_INT == 26) {
            authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_BEHIND;
        }
        updateScreenSize(authPageOrientation);
        int dialogHeight = (int) (mScreenHeightDp / 3.5f);
        int dialogWidth = (int) (mScreenWidthDp - 30 * 2);
        mAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder().setSloganHidden(true).setLogoImgDrawable(mActivity.getResources().getDrawable(com.baozhun.mall.res.R.drawable.ic_logo_login)).setLogoOffsetY(80).setLogoHeight(80).setLogBtnToastHidden(true).setScreenOrientation(authPageOrientation)
                //设置状态栏属性
                .setNavHidden(true)
                .setLightColor(true)
                .setWebViewStatusBarColor(Color.TRANSPARENT)
                .setStatusBarColor(Color.TRANSPARENT)
                .setStatusBarUIFlag(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
                //电话号码属性
                .setNumberSizeDp(28)
                .setNumberColor(Color.parseColor("#333333"))
                //设置登录按钮属性
                .setLogBtnHeight(44)
                .setLogBtnBackgroundDrawable(mActivity.getResources().getDrawable(R.drawable.shape_bg_login_bt))
                .setLogBtnText(mActivity.getString(com.baozhun.mall.res.R.string.one_key_login_hint))
                //切换到其他登录方式
                .setSwitchAccHidden(true) // 不用sdk的，用自己添加的,sdk的切换时会有toast提示
                .setSwitchAccText(mActivity.getString(com.baozhun.mall.res.R.string.use_other_phone_login_hint))
                .setSwitchAccTextSizeDp(13)
                .setSwitchOffsetY(390 - 60)

                //设置隐私协议属性
                .setPrivacyOffsetY(440 - 60)
                .setPrivacyTextSizeDp(12)
                .setPrivacyState(false)
                .setCheckBoxHeight(12)
                .setCheckBoxMarginTop(2)
                .setCheckBoxWidth(12)
                .setUncheckedImgDrawable(mActivity.getResources().getDrawable(R.drawable.ic_unenable_protocol))
                .setCheckedImgDrawable(mActivity.getResources().getDrawable(R.drawable.ic_agree_protocol))
                .setVendorPrivacyPrefix("《")
                .setVendorPrivacySuffix("》")
//                .setAuthPageActIn("activity_close_enter", "activity_close_exit")
//                .setAuthPageActOut("activity_open_enter", "activity_open_exit")
                .setAppPrivacyOne("《厚积用户协议》", Constants.Url.USER_PROTOCOL)
//                .setAppPrivacyTwo("《同意平台发放预支积分协议》", Constants.Url.GIFT_POINT_PROTOCOL)
                .setPrivacyConectTexts(new String[]{"", ""})
                .setPrivacyBefore("我已阅读并同意履行")
                .setPrivacyEnd("相关权利及义务")
                .setProtocolGravity(Gravity.LEFT)
                .setAppPrivacyColor(Color.GRAY, Color.parseColor("#EE612E"))

                //二次弹窗属性
                .setPrivacyAlertIsNeedShow(true) //不显示二次弹框
                .setPrivacyAlertIsNeedAutoLogin(true)
                .setTapPrivacyAlertMaskCloseAlert(false) //设置二次隐私协议弹窗点击背景蒙层是否关闭弹窗。
                .setPrivacyAlertMaskIsNeedShow(true)
                .setPrivacyAlertTitleContent(mActivity.getResources().getString(com.baozhun.mall.res.R.string.warm_reminder))
                .setPrivacyAlertAlignment(Gravity.CENTER)
                .setPrivacyAlertBackgroundColor(Color.WHITE)
                .setPrivacyAlertOneColor(Color.parseColor("#EE612E"))
                .setPrivacyAlertTwoColor(Color.parseColor("#EE612E"))
                .setPrivacyAlertThreeColor(Color.parseColor("#EE612E"))
                .setPrivacyAlertOperatorColor(Color.parseColor("#EE612E"))
                .setPrivacyAlertWidth(dialogWidth).setPrivacyAlertCloseBtnShow(false)
                .setPrivacyAlertCloseImagDrawable(mActivity.getResources().getDrawable(com.baozhun.mall.res.R.drawable.ic_close_black))
                .setPrivacyAlertCloseImgWidth(20)
                .setPrivacyAlertCloseImgHeight(20)
                .setPrivacyAlertHeight(dialogHeight)
                .setPrivacyAlertCornerRadiusArray(new int[]{16, 16, 16, 16})
                .setPrivacyAlertTitleTextSize(18)
                .setPrivacyAlertTitleOffsetY(10)
                .setPrivacyAlertTitleColor(Color.BLACK)
                .setPrivacyAlertContentTextSize(16)
                .setPrivacyAlertContentColor(Color.parseColor("#666666"))
                .setPrivacyAlertContentBaseColor(Color.parseColor("#666666"))
                .setPrivacyAlertBtnGrivaty(new int[]{RelativeLayout.CENTER_VERTICAL, RelativeLayout.ALIGN_PARENT_RIGHT})
                .setPrivacyAlertBtnHorizontalMargin(50)
                .setPrivacyAlertContentVerticalMargin(15)
                .setPrivacyAlertContentHorizontalMargin(20)
                .setPrivacyAlertBtnHeigth(40)
                .setPrivacyAlertContentAlignment(Gravity.CENTER | Gravity.LEFT)
                .setPrivacyAlertBtnTextColor(Color.WHITE)
                .setPrivacyAlertBtnBackgroundImgDrawable(mActivity.getResources().getDrawable(R.drawable.shape_bg_login_bt))
                .setPrivacyAlertBtnWidth(140)
                .setPrivacyAlertBtnContent(mActivity.getResources().getString(com.baozhun.mall.res.R.string.read_and_agree))
                .setPrivacyAlertBefore("我已阅读并同意履行")
                .setPrivacyAlertEnd("相关权利及义务")
                .create());
    }

    /**
     * 初始化关闭按钮
     *
     * @return
     */
    private ImageView initCloseBtn() {
        ImageView pImageView = new ImageView(mContext);
        pImageView.setImageResource(com.baozhun.mall.res.R.drawable.ic_close_black);
        pImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        RelativeLayout.LayoutParams pParams = new RelativeLayout.LayoutParams(dp2px(20), dp2px(20));
        pParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
        pParams.setMargins(0, dp2px(56.0F), dp2px(12.0F), 0);
        pImageView.setLayoutParams(pParams);
        return pImageView;
    }

}
